﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Messaging;

using Happy.ExtentionMethods;
using Happy.Event.Offline;

namespace Happy.Event.MSMQ
{
    /// <summary>
    /// 基于MSMQ的离线事件队列。
    /// </summary>
    public sealed class MSMQOfflineEventQueue : IOfflineEventQueue
    {
        private readonly MessageQueue _queue;

        /// <summary>
        /// 构造方法。
        /// </summary>
        public MSMQOfflineEventQueue(string queueName)
        {
            queueName.MustNotNullAndNotWhiteSpace(queueName);

            _queue = GetQueue(queueName);
        }

        /// <inheritdoc />
        public void Send(OfflineEvent offlineEvent)
        {
            using (var ts = new MessageQueueTransaction())
            {
                ts.Begin();

                var message = new Message(offlineEvent, GetXmlMessageFormatter());

                _queue.Send(message);

                ts.Commit();
            }
        }

        /// <inheritdoc />
        public OfflineEvent Receive()
        {
            using (var ts = new MessageQueueTransaction())
            {
                var message = _queue.Receive();

                message.Formatter = GetXmlMessageFormatter();

                return (message.Body as OfflineEvent);
            }
        }

        private static MessageQueue GetQueue(string queueName)
        {
            var queuePath = string.Format(@".\private$\{0}", queueName);

            if (MessageQueue.Exists(queuePath))
            {
                return new MessageQueue(queuePath);
            }

            return MessageQueue.Create(queuePath);
        }

        private static XmlMessageFormatter GetXmlMessageFormatter()
        {
            return new XmlMessageFormatter(new Type[] { typeof(OfflineEvent) });
        }
    }
}
